package com.hlk.hlk_blog.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hlk.hlk_blog.entity.Tag;
import com.hlk.hlk_blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@SuppressWarnings("ALL")
@Controller
@RequestMapping("/admin")
public class TagController {
    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String tags(@RequestParam(value = "pageNum", defaultValue = "1", required = false) Integer pageNum,
                       Model model) {
        PageHelper.startPage(pageNum, 5);
        List<Tag> tags = tagService.getAllTags();
        PageInfo<Tag> pageInfo = new PageInfo<>(tags);
        model.addAttribute("pageInfo", pageInfo);
        return "admin/tags";
    }

    /*
     * 跳转tag新增页面
     */
    @GetMapping("/tags/input")
    public String toAddTag(Model model) {
        //返回一个tag对象给前端th:object
        model.addAttribute("tag", new Tag());
        return "admin/tags-input";
    }

    /*
     * 跳转tag编辑页面
     */
    @GetMapping("/tags/{id}/input")
    public String toEditTag(@PathVariable Long id, Model model) {
        model.addAttribute("tag", tagService.getTagById(id));
        return "admin/tags-input";
    }

    /*
     * 新增
     */
    @PostMapping("/tags")
    public String addTags(Tag tag, RedirectAttributes attributes) {
        Tag name = tagService.getTagByName(tag.getName());
        if (name != null) {
            attributes.addFlashAttribute("mssage", "不能添加重复的标签");
            return "redirect:/admin/tags/input";
        } else {
            tagService.saveTag(tag);
            attributes.addFlashAttribute("mssage", "添加成功");
        }
        return "redirect:/admin/tags";
    }

    /*
     * 编辑
     */
    @PostMapping("/tags/{id}")
    public String editTag(@PathVariable Long id, Tag tag, RedirectAttributes attributes) {
        Tag name = tagService.getTagByName(tag.getName());
        if (name != null) {
            attributes.addFlashAttribute("mssage", "修改失败，标签名称重复！");
            return "redirect:/admin/tags/input";
        } else {
            tagService.updateTag(tag);
            attributes.addFlashAttribute("mssage", "修改成功");
        }
        return "redirect:/admin/tags";
    }

    /*
     *删除tag
     */
    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes) {
        tagService.deleteTag(id);
        attributes.addFlashAttribute("mssage", "删除成功");
        return "redirect:/admin/tags";
    }
}
